import { createRouter, createWebHashHistory, RouteRecordRaw, useRoute } from "vue-router";
import LoginVue from "../views/login/index.vue";
import { useUserStore } from "@/store/user";
import { userInfoApi } from "../http/api";
import { ElMessage } from "element-plus";
const routes: RouteRecordRaw[] = [
  {
    path: "/login",
    component: LoginVue,
  },
  {
    path: "/",
    redirect: "/index"
  },
  {
    path: "/",
    component: () => import("../views/home/index.vue"),
    children: [
      { path: "index", component: () => import("../views/index/index.vue") }
    ]
  },
];

const router = createRouter({
  routes,
  history: createWebHashHistory(),
});

const route = useRoute();
router.beforeEach((to, from, next) => {
  let token = localStorage.getItem("token")
  const store = useUserStore();
  if (token && store.menus.length == 0) {
    userInfoApi().then((res) => {
      if (res.code === 200) {
        store.menus = res.data.menus;
        store.username = res.data.username;
        //  动态生成路由
        store.routes.forEach((p) => {
          const route: RouteRecordRaw = {
            path: "/" + p.name,
            name: p.name,
            meta: {
              // 在meta里面把对应的中文存起来，然后在路由里面获取，以生成面包屑的中文
              title: p.title
            },
            component: () => import("../views/home/index.vue"),
            children: p.children.map((item) => ({
              path: item.name,
              name: item.name,
              meta: {
                title: item.title
              },
              component: () => import(`../views/${p.name}/${item.name}.vue`)
            }))
          }
          // 访问一级路由，跳转到第一个子路由
          if (p.children[0]) {
            route.redirect = `/${p.name}/${p.children[0].name}`
          }
          router.addRoute(route)
        })
        next(to.fullPath)
      }
    })
  } else if (!token && to.path !== "/login") {
    ElMessage.error("请先登录")
    next("/login")
  } else if (token && store.menus.length !== 0 && to.path === "/login") {
    ElMessage.warning("请先退出登录再重新登陆")
    next(from.fullPath)
  } else {
    next();
  }
})

export default router;
